<template>
  <div class="app-container bg-white">
    <!-- 表头 -->
    <div class="page-body">
      <div class="full-width" id="mul_select">
          <el-form :model="queryForm" ref="queryFormRef" :inline="true" size="small">
            <el-form-item>
                <el-input size="small" placeholder="请输入商品名称" v-model.trim="queryForm.search"></el-input>
            </el-form-item>
            <el-form-item>
                <el-cascader size="small" :options="classDataList" placeholder="请选择商品分类" :show-all-levels="false"
                  v-model="queryForm.classIds" :props="{ value: 'id', label:'title', children:'goodsCategoryModelList' }"></el-cascader>
            </el-form-item>
            <el-form-item>
                <el-select size="small" v-model="queryForm.type" placeholder="请选择奖励比例" clearable >
                    <el-option v-for="item in proportionDataList" :key="'proportion' + item.value" :label="item.name" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-select size="small" v-model="queryForm.status" placeholder="请选择分享状态" clearable>
                    <el-option v-for="item in statusDataList" :key="'status' + item.value" :label="item.name" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-button size="small" type="primary" @click="getPageDataList()">查询</el-button>
            <el-button size="small" @click="resetOption()">重置</el-button>
        </el-form>
      </div>
       <div>
            <el-button size="mini" type="success" icon="el-icon-document-add" @click="addSharedGood()">添加商品</el-button>
            <el-button size="mini" type="primary" icon="el-icon-sell" @click="editAllOption()">批量编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeSelectOption()">批量删除</el-button>
        </div>
        <el-table class="margin_top_20" :data="pageData" v-loading="loading" stripe @selection-change="handleSelectionChange" :header-cell-style="tableHeaderStyle" >
            <el-table-column type="selection" width="42"></el-table-column>
            <el-table-column label="序号" type="index" width="50"></el-table-column>
            <el-table-column label="商品图片">
                <template slot-scope="scope">
                    <img :src="baseImgUrl + '/' + scope.row.surfaceImg" class="shop_avator" v-if="scope.row.surfaceImg">
                </template>
            </el-table-column>
            <el-table-column prop="title" label="商品名称"></el-table-column>
            <el-table-column prop="goodsNo" label="商品编码"></el-table-column>
            <el-table-column prop="className" label="商品分类"></el-table-column>
            <el-table-column prop="minSupplyPrice" label="成本价（元）">
              <template slot-scope="scope">
                {{scope.row.minSupplyPrice}} ~ {{scope.row.maxSupplyPrice}}
              </template>
            </el-table-column>
            <el-table-column prop="minPrice" label="售价（元）">
              <template slot-scope="scope">
                {{scope.row.minPrice}} ~ {{scope.row.maxPrice}}
              </template>
            </el-table-column>
            <!-- <el-table-column label="商家佣金比率">
                <template slot-scope="scope">
                <p v-for="(item,index) in scope.row.levelList" :key="index">
                    {{item.levelName}}:{{item.shareCustomerRatio}}%({{scope.row.minPrice*item.shareCustomerRatio/100}}~{{scope.row.maxPrice*item.shareCustomerRatio/100}})</p>
                </template>
            </el-table-column> -->
            <el-table-column label="分享客佣金比率">
                <template slot-scope="scope">
                <p v-for="(item,index) in scope.row.levelList" :key="index">
                    {{item.levelName}}:{{item.shareCustomerRatio / scope.row.minSupplyPrice * 100}}%({{item.shareCustomerRatio}}元)</p>
                </template>
            </el-table-column>
            <el-table-column label="邀请人佣金比率">
                <template slot-scope="scope">
                <p v-for="(item,index) in scope.row.levelList" :key="index">
                    {{item.levelName}}:{{item.inviterRatio / scope.row.minSupplyPrice * 100}}%({{item.inviterRatio}}元)</p>
                </template>
            </el-table-column>
            <el-table-column label="是否上架">
                <template slot-scope="scope">
                <el-switch @change="updateStatusOption($event, scope.row, scope.$index)" :value="scope.row.status == 1"></el-switch>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
                <template slot-scope="scope">
                    <el-button size="mini" @click="editOneOption(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="removeOption(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="text-center">
        <el-pagination background @size-change="handleSizeChange" @current-change="handlePagingChange" :current-page="pageIndex" :page-sizes="pageSizes"
          :page-size="pageSize" :layout="paginationLayout" :total="pageCount">
        </el-pagination>
    </div>

    <shared-list-dialog :single="isSingleMode" :isShow.sync="isShowDialog" :list="selectDataList" :levelList="settingDataList" @close="closeDialog" @confirm="confirmDialog"/>
  </div>
</template>

<script>
  import Setting from '@/settings';
  import { GetStoreClassList } from '@/views/store-management/services/index';
  import sharedListDialog from '@/views/shared-management/components/sharedListDialog';
  import { GetShareGoodsList, GetSharedSettings, UpdateShareGoodsStatus, RemoveShareGoodsItem, RemoveShareGoodsBatch } from '@/views/shared-management/services/index';

  export default {
    components: {
      sharedListDialog
    },
    data() {
      return {
        settingDataList: [],
        statusDataList: [
          { name: '未生效', value: 0 },
          { name: '生效', value: 1 }
        ],
        proportionDataList: [
          { name: '全部奖励比率', value: '' },
          { name: '默认奖励比率', value: 0 },
          { name: '自定义奖励比率', value: 1 }
        ],
        classDataList: [],
        queryForm: {
            search: '', // 商品名称搜索
            classIds: [], // 商品分类id
            type:	'', // 分佣类型 0 默认 1 自定义
            status:	'' // 0 未生效 1生效
        },
        pageData: [],
        pageCount: 0,
        pageIndex: 1,
        loading: false,
        pageSize: Setting.defaultTablePaginationSize,
        pageSizes: Setting.tablePaginationSizes,
        tableHeaderStyle: Setting.tableHeaderStyle,
        paginationLayout: Setting.tablePaginationLayout,
        multipleSelection: [],

        baseImgUrl: process.env.VUE_APP_FILE_URL,
        
        isSingleMode: true,
        isShowDialog: false,
        selectDataList: []
      }
    },
    mounted() {
      this.loading = true;
      this.getStoreClassList();
      this.getPageDataSettings();
    },
    methods: {
      editOneOption(rowData) {
        this.isShowDialog = true;
        this.selectDataList = [rowData];
        this.isSingleMode = true;
      },
      editAllOption() {
        if (!this.multipleSelection || !this.multipleSelection.length) {
          this.$message.warning('请选择需要编辑的商品列表!');
          return;
        }
        this.isShowDialog = true;
        this.selectDataList = this.multipleSelection;
        this.isSingleMode = false;
      },
      closeDialog() {
        this.isShowDialog = false;
      },
      confirmDialog() {
        this.getPageDataList();
        this.closeDialog();
      },
      // 删除操作
      removeOption(rowId) {
        this.$confirm('是否确认要移除所选中的商品，移除后此商品不在分享专区显示?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true;
              instance.confirmButtonText = '加载中...';
              RemoveShareGoodsItem({ id: row.id })
              .then(data => {
                instance.confirmButtonLoading = false;
                if (data.code == 200) {
                  done();
                  this.$message.success('删除成功!');
                  this.getPageDataList();
                } else {
                  this.$message.error('删除失败!');
                }
              })
              .catch(error => {
                instance.confirmButtonLoading = false;
              })
            } else {
              done();
            }
          }
        })
      },
      // 批量删除操作
      removeSelectOption() {
        if (!this.multipleSelection || !this.multipleSelection.length) {
          this.$message.warning('请选择需要删除的商品!');
          return;
        }
        this.$confirm('是否确认要移除所选中的商品，移除后此商品不在分享专区显示?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true;
              instance.confirmButtonText = '加载中...';
              RemoveShareGoodsBatch({ shareGoodsList: this.multipleSelection.map(item => item.id) })
              .then(data => {
                instance.confirmButtonLoading = false;
                if (data.code == 200) {
                  done();
                  this.$message.success('删除成功!');
                  this.getPageDataList();
                } else {
                  this.$message.error('删除失败!');
                }
              })
              .catch(error => {
                instance.confirmButtonLoading = false;
              })
            } else {
              done();
            }
          }
        })
      },
      // 修改上下架状态
      updateStatusOption(event, rowData, rowIndex) {
        UpdateShareGoodsStatus({
            id: rowData.id,
            status: rowData.status == 0 ? 1 : 0
        })
        .then(data => {
          if (data.code == 200) {
            this.$message.success('修改成功!');
            rowData.status = rowData.status == 0 ? 1 : 0;
          } else {
            this.$message.error('修改失败!');
          }
        })
      },
      // 分页操作
      handlePagingChange(event) {
        this.pageIndex = event;
        this.getPageDataList();
      },
      handleSizeChange(event) {
        this.pageIndex = 1;
        this.pageSize = event;
        this.getPageDataList();
      },
      handleSelectionChange(event) {
        this.multipleSelection = event
      },
      // 获取页面数据
      getPageDataList() {
        this.loading = true;
        GetShareGoodsList({
            categoryId: this.queryForm.classIds[this.queryForm.classIds.length - 1],
            refundType:	this.queryForm.type,
            status:	this.queryForm.status,
            search: this.queryForm.search,
            pageNum: this.pageIndex,
            pageSize: this.pageSize
        })
        .then(data => {
            this.loading = false;
            if (data.code != 200) {
                this.$message.error('加载失败，请重新刷新列表');
                return;
            }
            this.pageData = data.data.list.map(item => {
                item.className = '';
                if (item.category) {
                    const finder = this.classDataList.find(li => li.id == JSON.parse(item.category)[0]);
                    if (finder) {
                        item.className = finder.title;
                        const finder2 = finder.goodsCategoryModelList.find(li => li.id == JSON.parse(item.category)[1]);
                        if (finder2) {
                            // item.className += '/' + finder2.title;
                            item.className = finder2.title;
                            const finder3 = finder2.goodsCategoryModelList.find(li => li.id == JSON.parse(item.category)[2]);
                            if (finder3) {
                                // item.className += '/' + finder3.title;
                                item.className = finder3.title;
                            }
                        }
                    }
                }
                return item;
            });
            this.pageCount = data.data.total;
        })
        .catch(error => {
            this.loading = false;
            this.$message.error(error);
        })
      },
      resetOption() {
        this.queryForm.search = '';
        this.queryForm.classIds = [];
        this.queryForm.type = '';
        this.queryForm.status = '';
        this.pageIndex = 0;
        this.getPageDataList();
      },
      // 获取商品分类数据
      getStoreClassList() {
        GetStoreClassList()
        .then(data => {
          if (data.code == 200) {
            this.classDataList = data.data;

            this.getPageDataList();
          }
          this.loading = false;
        })
        .catch(error => {
          this.loading = false;
        })
      },
      getPageDataSettings() {
        GetSharedSettings()
        .then(data => {
          if (data.code == 200) {
            this.settingDataList = data.data.levelList.map(item => {
                delete item.id;
                return item;
            })
          }
        })
      },
      // 进入添加商品的页面
      addSharedGood() {
        this.$router.push({ name: 'AddSharedStore' });
      }
    }
  }
</script>

<style lang="scss" scoped>
.shop_avator {
  width: 64px;
  height: 64px;
  vertical-align: middle;
}
</style>
